package com.yunhe.option.service.base.impl;

import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.util.QueryUtil;
import com.yunhe.common.util.StringUtil;
import com.yunhe.option.domain.base.Whether;
import com.yunhe.option.repository.base.WhetherRepository;
import com.yunhe.option.service.base.WhetherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 是否类型Service
 * @desc 是否类型服务类实现
 * @author anmeiyi
 */
@Service
public class WhetherServiceImpl implements WhetherService {
    @Autowired
    private WhetherRepository whetherRepository;

    private void processBeforeSave(Whether whether)
            throws ArgumentErrorException, UniqueConstraintsException {
        //判断是否类型代码、编号、标题是否为空
        if(whether.getCode() == null
                || StringUtil.isEmpty(whether.getName())
                || StringUtil.isEmpty(whether.getTitle())) {
            throw new ArgumentErrorException("是否类型代码、编号、标题不能为空");
        }
        //判断代码是否已存在
        Whether categoryByCode = this.findByCode(whether.getCode());
        if(categoryByCode != null) {
            if(whether.getId() == null || categoryByCode.getId().longValue() != whether.getId().longValue()) {
                throw new UniqueConstraintsException("该是否类型代码已存在");
            }
        }
        //判断编号是否已存在
        Whether categoryByName = this.findByName(whether.getName());
        if(categoryByName != null) {
            if(whether.getId() == null || categoryByName.getId().longValue() != whether.getId().longValue()) {
                throw new UniqueConstraintsException("该是否类型编号已存在");
            }
        }
        //如果序号为空，则默认等于代码
        if(whether.getSn() == null && whether.getCode() != null) {
            whether.setSn(whether.getCode());
        }
    }

    /**
     * 新增是否类型
     * @param whether 是否类型对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public Whether createWhether(Whether whether)
            throws ArgumentErrorException, UniqueConstraintsException {
        whether.setId(null);
        processBeforeSave(whether);
        return whetherRepository.save(whether);
    }

    /**
     * 删除是否类型
     * @param whetherId 是否类型Id
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void deleteWhether(Long whetherId) {
        whetherRepository.deleteById(whetherId);
    }

    /**
     * 更新是否类型(全部字段）
     * @param whether 是否类型对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public Whether updateWhether(Whether whether)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        boolean exists = whether.getId() != null && whetherRepository.existsById(whether.getId());
        if(!exists) {
            throw new ObjectNotFoundException("找不到ID为" + whether.getId() + "的是否类型");
        }
        processBeforeSave(whether);
        return whetherRepository.save(whether);
    }

    /**
     * 更新是否类型（部分字段）
     * @param whetherId 是否类型对象
     * @param code
     * @param name
     * @param title
     * @param sn
     * @param activity
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public Whether updateWhether(Long whetherId, Long code, String name, String title, Long sn, Boolean activity)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        Whether whether = this.findByWhetherId(whetherId);
        if(whether == null) {
            throw new ObjectNotFoundException("找不到ID为" + whetherId + "的是否类型");
        }
        Optional.ofNullable(code).ifPresent(whether::setCode);
        Optional.ofNullable(name).ifPresent(whether::setName);
        Optional.ofNullable(title).ifPresent(whether::setTitle);
        Optional.ofNullable(sn).ifPresent(whether::setSn);
        Optional.ofNullable(activity).ifPresent(whether::setActivity);
        processBeforeSave(whether);
        return whetherRepository.save(whether);
    }

    /**
     * 获得全部是否类型对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public Iterable<Whether> findIndustryCategories() {
        return whetherRepository.findAll(QueryUtil.defaultSort());
    }

    /**
     * 根据编号获得是否类型对象
     * @param name
     */
    private Whether findByName(String name) {
        return whetherRepository.findByName(name);
    }

    /**
     * 根据代码获得是否类型对象
     * @param code
     */
    private Whether findByCode(Long code) {
        return whetherRepository.findByCode(code);
    }

    /**
     * 根据ID获得是否类型对象
     * @param whetherId
     * @return
     */
    private Whether findByWhetherId(Long whetherId) {
        return whetherRepository.findById(whetherId).orElse(null);
    }
}
